package tau.dimes.visualization.servlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import tau.dimes.beans.LoginBean;
import tau.dimes.web.UserFiles;

public class FileProvider implements IProvider
{
	private ServletContext _servletContext;
	private LoginBean _loginBean;

	public FileProvider()
	{

	}

	@Override
	public Document GetXMLContent(Map<String, String> attributes)
	{
		if (!attributes.containsKey("Filename"))
			return null;

		try
		{
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource is = new InputSource();

			// String filePath = String.format("/Data/%s",
			// attributes.get("Filename"));
			// InputStream isData =
			// _servletContext.getResourceAsStream(filePath);

			String filename = attributes.get("Filename");
			UserFiles userFiles = new UserFiles(_loginBean.getUsername(), _servletContext);
			InputStream isData = new FileInputStream(userFiles.getFile(filename));

			is.setByteStream(isData);
			return db.parse(is);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public void setServerContext(ServletContext serverContext)
	{
		_servletContext = serverContext;
	}

	@Override
	public void setLoginBean(LoginBean loginBean)
	{
		_loginBean = loginBean;
	}
}
